package com.whjfxx.terminal.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whjfxx.terminal.base.BaseController;
import com.whjfxx.terminal.biz.param.FuncPageParam;
import com.whjfxx.terminal.biz.param.FuncParam;
import com.whjfxx.terminal.biz.param.SearchParam;
import com.whjfxx.terminal.biz.service.PoFuncService;
import com.whjfxx.terminal.biz.vo.FuncVo;
import com.whjfxx.terminal.commons.Result;
import com.whjfxx.terminal.commons.SelectVo;
import com.whjfxx.terminal.entity.PoFunc;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * Created by b.c on 2022/6/7 16:29
 */
@RestController
@Log4j2
@RequestMapping("func")
public class PoFuncController extends BaseController {

    @Autowired
    PoFuncService poFuncService;

    @GetMapping("page")
    public Result<Page<FuncVo>> pageList(SearchParam<FuncPageParam> param) {
        Page<FuncVo> page = poFuncService.pageList(param);
        return Result.success(page);
    }

    @GetMapping("selectList")
    public Result<List<SelectVo<Long, String>>> selectList(@RequestParam(value = "appId", required = false) Long appId) {
        if (Objects.isNull(appId)) {
            return Result.success(Collections.emptyList());
        }
        LambdaQueryWrapper<PoFunc> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PoFunc::getAppId, appId);
        List<PoFunc> poFuncs = poFuncService.list(wrapper);
        if (CollectionUtils.isEmpty(poFuncs)) {
            return Result.success(Collections.emptyList());
        }
        List<SelectVo<Long, String>> selectVos = poFuncs.stream().map(a -> SelectVo.create(a.getId(), a.getFuncName())).collect(Collectors.toList());
        return Result.success(selectVos);
    }

    @PostMapping("save")
    public Result<Object> save(@Validated FuncParam param) {
        if (Objects.isNull(param.getId())) {
            poFuncService.insertSave(param);
        } else {
            poFuncService.updateSave(param);
        }
        return Result.success();
    }

    @PostMapping("delete")
    public Result<Object> delete(@Validated @RequestParam("id") Long id) {
        poFuncService.delete(id);
        return Result.success();
    }

}
